import { Module } from 'vuex'
import { IRootState } from '@/store/type'
import { ILogin } from './type'
import {
  loginRequest,
  userInfoRequest,
  subCountRequest,
  likeListRequest,
  songInfoRequest,
  logoutRequest
} from '@/service/home/home'
import cache from '@/utils/cache/cache'
const loginModule: Module<ILogin, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      profile: {},
      userInfo: {},
      likeList: [],
      likeSongInfo: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, payLoad: any) {
      state.token = payLoad
    },
    //个人部分信息
    changeProfile(state, payLoad: any) {
      state.profile = payLoad
    },
    //个人全部信息
    changeUseInfo(state, payLoad: any) {
      state.userInfo = payLoad
    },
    //喜欢列表
    changeLikeList(state, payLoad: any) {
      state.likeList = payLoad
    },
    //喜欢列表的歌曲信息
    changeLikeSongInfo(state, payLoad: any) {
      state.likeSongInfo = payLoad
    }
  },
  actions: {
    async getUseInfo({ commit }, payLoad: any) {
      const { name, password } = payLoad
      const loginUserInfo = await loginRequest(name, password)

      commit('changeToken', loginUserInfo.token)
      if (loginUserInfo.token) cache.setCache('token', loginUserInfo.token)
      console.log(loginUserInfo.profile.userId)

      //拿到id进行请求
      const requestInfo = {
        id: loginUserInfo.profile.userId,
        loading: false
      }
      //请求用户信息
      const userInfo = await userInfoRequest(requestInfo.id, requestInfo.loading)
      console.log(userInfo)
      //拿到个人的profile
      commit('changeProfile', userInfo.profile)
      cache.setCache('profile', userInfo.profile)
      //拿到所有的个人信息
      commit('changeUseInfo', userInfo)
      cache.setCache('useInfo', userInfo)
      //获得用户收藏歌曲歌单 数量
      const subCount = await subCountRequest()
      console.log(subCount)
      //获得用户的喜欢列表
      const likeList = await likeListRequest(requestInfo.id)
      console.log(likeList)
      commit('changeLikeList', likeList.ids)
      cache.setCache('likeList', likeList.ids)
      //获取喜欢列表的音乐信息
      const likeSongInfo = await songInfoRequest(likeList.ids)
      commit('changeLikeSongInfo', likeSongInfo.songs)
      cache.setCache('likeInfo', likeSongInfo.songs)
      console.log(likeSongInfo)
    },
    //退出登录
    async logout() {
      const userLogout = await logoutRequest()
    },
    setStore({ commit }) {
      commit('changeToken', cache.getCache('token'))
      commit('changeProfile', cache.getCache('profile'))
      commit('changeUseInfo', cache.getCache('useInfo'))
      commit('changeLikeList', cache.getCache('likeList'))
      commit('changeLikeSongInfo', cache.getCache('likeInfo'))
    }
  }
}
export default loginModule
